package com.whsxt.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.whsxt.config.WxAutoConfiguration;
import com.whsxt.config.WxProperties;
import com.whsxt.constant.QueueConstant;
import com.whsxt.model.WxMsgModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-23 14:55
 * @Description:
 */
@Component
@Slf4j
public class WxMsgListener {


    @Autowired
    private WxProperties wxProperties;

    @Autowired
    private WxAutoConfiguration wxAutoConfiguration;

    @Autowired
    private RestTemplate restTemplate;


    @RabbitListener(queues = QueueConstant.WECHAT_SEND_QUEUE, concurrency = "3-5")
    public void wxMsgHandler(Message message, Channel channel) {
        String msgStr = new String(message.getBody());
        WxMsgModel wxMsgModel = JSON.parseObject(msgStr, WxMsgModel.class);
        try {
            realSendWxMsg(wxMsgModel);

            //成功，进入数据库
            //签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("微信公众号发送消息成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信公众号发送消息失败");
        }


    }


    /**
     * 发送微信公众号消息
     *
     * @param wxMsgModel
     */
    private void realSendWxMsg(WxMsgModel wxMsgModel) {
        //发消息
        //往一个地址发一个请求
        String sendMsgUrl = wxProperties.getSendMsgUrl();
        String realUrl = String.format(sendMsgUrl, wxAutoConfiguration.getWxAccessToken());

        String result = restTemplate.postForObject(realUrl, wxMsgModel, String.class);
        System.out.println(result);
    }


}
